/**
 * ModuleName: wx_mp_account`
 * Company: 麦田网络
 * @author Kenny
 * @date 2018/12/19
 * @version 1.0
 * Description: 微信号管理模块
 * 
 * ......................我佛慈悲......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *                       
 *..................佛祖开光 ,永无BUG...................
 * 
 */
'use strict';
var rest = require('../utils/restful');
var wxHelper = require('../utils/wxHelper')

module.exports = function (Wxmpaccount) {
    //参数长度校验
    Wxmpaccount.validatesLengthOf('app_name', {
        min: 4,
        message: {
            min: 'app_name is too short!'
        }
    });
    //参数长度校验
    Wxmpaccount.validatesLengthOf('app_name', {
        max: 12,
        message: {
            max: 'app_name is too long!'
        }
    });
    //参数长度校验
    Wxmpaccount.validatesLengthOf('app_secret', {
        is: 32,
        message: {
            is: 'app_secret is wrong of length!'
        }
    });
    //校验参数唯一性
    Wxmpaccount.validatesUniquenessOf('app_id', {
        message: 'app_id is not unique!'
    });

    var fixedAccountData = function (ctx, next) {
        if (ctx.instance && ctx.isNewInstance && !ctx.instance.app_token) {
            //自动生成TOKEN
            ctx.instance.app_token =
                ''.random(32, {
                    numbers: false
                });
        }
        if (ctx.instance && ctx.isNewInstance && !ctx.instance.EncodingAESKey) {
            //自动生成EncodingAESKey
            ctx.instance.EncodingAESKey =
                ''.random(43, {
                    numbers: false
                });
        }
        next();
    }

    var replaceMenu = function (appid, menu, cb) {
        //查找appid相关号
        Wxmpaccount.find({
            where: {
                app_id: appid
            }
        }, async function (err, results) {
            if (err || !results || results.length <= 0)
                cb(null, "error")
            //将模型取出
            var singleAccModel = results[0];
            var api = wxHelper.initApp(singleAccModel);
            if (singleAccModel.app_menu === menu) {
                return cb(null, singleAccModel.app_menu)
            }

            var result = await api.createMenu(JSON.parse(menu));
            if (result.errcode === 0 && result.errmsg === "ok") {
                singleAccModel.app_menu = menu;
                singleAccModel.save();
            }

            return cb(null, result)
        })
    }

    var getCurrentMenu = function (appid, cb) {
        //查找appid相关号
        Wxmpaccount.find({
            where: {
                app_id: appid
            }
        }, async function (err, results) {
            if (err || !results || results.length <= 0)
                return cb("appid is not config in system")
            var singleAccModel = results[0];
            var api = wxHelper.initApp(singleAccModel);

            var result = await api.getMenu();

            if (singleAccModel.app_menu !== JSON.stringify(result.menu)) {
                singleAccModel.app_menu = JSON.stringify(result.menu);
                singleAccModel.save();
            }

            return cb(null, result.menu)
        })
    }
    //获取当前公众号的菜单，更新到库中
    Wxmpaccount.getCurrentMenu = getCurrentMenu;
    //更换某个公众号的菜单
    Wxmpaccount.replaceMenu = replaceMenu;
    //保存前确保数据完整性
    Wxmpaccount.observe('before save', fixedAccountData);

    //远程服务函数 SAAS模式 - server as a service
    Wxmpaccount.remoteMethod('replaceMenu', {
        http: {
            path: '/:appid/menu/replace',
            verb: 'post'
        },
        accepts: [{
                arg: 'appid',
                type: 'string'
            },
            {
                arg: 'menu',
                type: 'string'
            }
        ],
        returns: {
            arg: 'data',
            type: 'object'
        }
    })
    Wxmpaccount.remoteMethod('getCurrentMenu', {
        http: {
            path: '/:appid/menu',
            verb: 'get'
        },
        accepts: [{
            arg: 'appid',
            type: 'string'
        }],
        returns: {
            arg: 'menu',
            type: 'object'
        }
    })
};